package cn.vc.shop.controller;

import cn.vc.auth.entity.po.VUser;
import cn.vc.basicmodule.entity.Result;
import cn.vc.shop.entity.po.OrderForGoods;
import cn.vc.shop.service.CommodityService;
import cn.vc.shop.service.OrderForGoodsService;
import cn.vc.shop.util.SecurityUtil;
import cn.vc.wallet.feign.clients.WalletClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 购买接口
 * @author mo
 * @日期: 2024-05-04 00:14
 **/
@RestController
@RequestMapping("/buy")
public class BuyController {
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private WalletClient walletClient;
    @Autowired
    private OrderForGoodsService orderForGoodsService;


    /**
     * 购买秒杀商品
     * @param id 商品ID
     * @param num 购买数量
     * @return
     */
    @PostMapping("/seckill")
    public Result<?> buySeckill(@RequestParam Long id, @RequestParam Integer num) {
        VUser myUser = SecurityUtil.getUser();
        if (myUser==null) return Result.NOT_LOGGED_IN();
        // 1、商品数量减一 并 获取订单
        Result<OrderForGoods> result = commodityService.buySeckill(myUser.getId(), id, num);
        // 购买失败
        if (result.getCode()==0) return result;
        // 3、写入订单
        boolean bo = orderForGoodsService.insert(result.getData());
        return bo?result:new Result<>(0,null,"购买失败！");
    }

    /**
     * 购买普通商品
     * @param id 商品ID
     * @param num 购买数量
     * @return
     */
    @PostMapping("/common")
    public Result<?> buyCommon(@RequestParam Long id, @RequestParam Integer num) {
        VUser myUser = SecurityUtil.getUser();
        if (myUser==null) return Result.NOT_LOGGED_IN();
        // 1、商品数量减一 并 获取订单
        Result<OrderForGoods> result = commodityService.buyCommon(myUser.getId(), id, num);
        // 购买失败
        if (result.getCode()==0) return result;
        // 3、写入订单
        boolean bo = orderForGoodsService.insert(result.getData());
        return bo?result:new Result<>(0,null,"购买失败！");
    }

}
